package com.example.mydemo.controller.hc;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mydemo.config.ReVo;
import com.example.mydemo.entity.*;
import com.example.mydemo.entity.domain.MenuVO;
import com.example.mydemo.entity.domain.ResponseDTO;
import com.example.mydemo.log.LogRequest;
import com.example.mydemo.mapper.ClockMapper;
import com.example.mydemo.mapper.DepMapper;
import com.example.mydemo.mapper.UsersMapper;
import com.example.mydemo.model.*;
import com.example.mydemo.service.DepService;
import com.example.mydemo.service.IMenuService;
import com.example.mydemo.service.UserService;
import com.example.mydemo.service.impl.ClockService;
import com.example.mydemo.util.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;


@Controller
@RequestMapping()
public class hController {
    /**
     * 去到.html页面
     */
    @Autowired
    private UsersMapper userMapper;
    @Autowired
    private DepMapper depMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DepService depService;
    @Autowired
    private ClockMapper IClockService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IMenuService menuService;
    @GetMapping("/getUserById")
    @ResponseBody
    public ResponseDTO<Users> getList(
            @RequestParam Long id) {
        Users users = userMapper.selectById(id);
        if (users.getIsDelete()==0L){
            return new ResponseDTO<>(200, "获取信息成功！", users);
        }else {
            return new ResponseDTO<>(200, "获取信息失败！", users);
        }
    }
    @LogRequest
    @GetMapping("/getpage")
    @ResponseBody
//    @RequestParam String username,
    public tableVO getpage(@RequestParam Long page, @RequestParam Long limit, @RequestParam(defaultValue = "") String searchParams) {
        List<Users> userList = userMapper.selectList(null);
        Page<Users> usepage = new Page<>(page, limit); // 创建分页对象，当前页为1，每页显示5条记录
        IPage<Users> userPage = userMapper.selectPage(usepage, new UpdateWrapper<Users>().eq("is_delete", 0L));
        System.out.println("Hello ！！！！！");
        tableVO a = new tableVO();
        a.setCode(0L);
        a.setMsg("");
        if (searchParams == "") {
            a.setData(userPage.getRecords());
        } else {
            a.setData(userService.selectByName(searchParams));
        }
        a.setCount(userPage.getTotal());
        return a;
    }
    @GetMapping("/getuserpage")
    @ResponseBody
//    @RequestParam String username,
    public tableVO getuserpage() {
        Page<Users> usepage = new Page<>(1, 1000); // 创建分页对象，当前页为1，每页显示5条记录
        IPage<Users> userPage = userMapper.selectPage(usepage, new UpdateWrapper<Users>().eq("is_delete", 0L));
        System.out.println("Hello ！！！！！");
        tableVO a = new tableVO();
        a.setCode(0L);
        a.setMsg("");
        a.setData(userPage.getRecords());
        a.setCount(userPage.getTotal());
        return a;
    }
    @PostMapping("/selectUser")
    @ResponseBody
    public ResponseDTO<List<UserVO>> selectUser(@RequestParam String name, @RequestParam Long page, @RequestParam Long limit) {
        List<UserVO> user = userService.selectByName(name);
        return new ResponseDTO<>(200, "获取用户信息成功！", user);
    }

    @GetMapping("/getdeppage")
    @ResponseBody
    public tableVO selectDeptCount(@RequestParam Long page, @RequestParam Long limit, @RequestParam(defaultValue = "") String searchParams) {
        Page<DepVO> deppage = new Page<>(page, limit); // 创建分页对象，当前页为1，每页显示5条记录
        List<DepVO> b = new ArrayList<>();
        if (searchParams == "") {
            b = depService.selectDeptCount();
        } else {
            b = depService.selectDeptCountByName(searchParams);
        }
        tableVO a = new tableVO();
        a.setCode(0L);
        a.setMsg("");
        a.setData(b);
        a.setCount((long) b.size());
        return a;
    }
    @PostMapping("/addDep")
    @ResponseBody
    public ResponseDTO<Dep> addDep(@RequestParam("dep") String dep) {
        Dep dep1 = new Dep();

        dep1.setDepname(dep);
        dep1.setCreateBy("syf");
        dep1.setCreateTime(new Date());
        depService.saveUser(dep1);
        return new ResponseDTO<Dep>(200, "添加信息成功！", dep1);
    }
    @PostMapping("/depDelete")
    @ResponseBody
    public ResponseDTO<Dep> depDelete(@RequestParam Long id) {
        depService.delete(id);
        return new ResponseDTO<>(200, "获取用户信息成功！", null);
    }
    @GetMapping("/getDepById")
    @ResponseBody
    public ResponseDTO<Dep> getDepById(
            @RequestParam Long id) {
        Dep dep = depMapper.selectById(id);
        if (dep.getIsDelete()==0L){
            return new ResponseDTO<>(200, "获取信息成功！", dep);
        }else {
            return new ResponseDTO<>(200, "获取信息失败！", dep);
        }
    }
    @PostMapping("/update-dep")
    public ResponseEntity<Boolean> updateDbParam(
            @RequestParam Long id,
            @RequestParam String dep
    ) {                Dep sysParam = new Dep();
        sysParam.setDepname(dep);
        int updated = depMapper.update(
                sysParam, // 显式传递实体对象
                new UpdateWrapper<Dep>().eq("depid", id)
        );
        return ResponseEntity.ok(updated > 0);
    }
    @LogRequest
    @GetMapping("/getpageToList")
    @ResponseBody
    public IPage<Users> getpageToList() {
        List<Users> userList = userMapper.selectList(null);
        Page<Users> page = new Page<>(1, 1000); // 创建分页对象，当前页为1，每页显示5条记录

        IPage<Users> userPage = userMapper.selectPage(page, new QueryWrapper<Users>().select());
        // Assert.isTrue(5 == userList.size(), "");
        userList.forEach(System.out::println);
//        System.out.println(userPage.getRecords());
//        for (Users users : userList){
//            System.out.println(users.getName() + '-' + users.getEmail() );
//        }
//            model.addAttribute("user", userPage.getPages());
        return userPage;
    }

    @RequestMapping("/tables")
    public String tables(Model model) {
        List<Users> findUser = userService.list();
        model.addAttribute("user", findUser);
        return "tables";
    }


    @GetMapping("/getList")
    @ResponseBody
    public ReVo getList(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "3") int size) {

        Page<Users> pageInfo = new Page<>(page, size); // 创建分页对象，当前页为1，每页显示10条记录

        IPage<Users> findUser = userService.page(pageInfo);

        ReVo reVo = new ReVo();

        reVo.setData(findUser.getRecords());
        reVo.setRecordsTotal(findUser.getTotal());

        reVo.setRecordsFiltered(20);

        // userService.list();
        return reVo;
    }


    @PostMapping("/dakaresult")
    @ResponseBody
//        @Cacheable(value = "dakaresult", key = "#name")
    public Boolean setdaka(@RequestParam String name) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        Users user1 = userMapper.selectOne(wrapper);
        //System.out.print(user);
        Clock findDaka = new Clock();
        long result = user1.getId();
        findDaka.setEmployeeId(result);
        findDaka.setClockTime(LocalDateTime.now());
//            System.out.println(redisUtil.getValue("name"));
        return IClockService.insert(findDaka)!=0;
    }

    @PostMapping("/debug")
    @ResponseBody
    public void debug() {
        redisUtil.set("debug", "false");
    }

    @LogRequest
    @PostMapping("/login")
    @ResponseBody
    public ResponseDTO<Users> login(@RequestParam String username, String email, String captcha, HttpServletRequest request) {
//            List<Users> findUser = userService.list();
//            model.addAttribute("user",findUser );
        HttpSession session = request.getSession();
        // 测试
        redisUtil.set("debug", "false");
        loginVO a = userService.login(username, email, captcha, session);
        Users userdata = (Users) session.getAttribute("user");

        redisUtil.set("userName",username );

        session.setMaxInactiveInterval(60 * 100);
        if (a.isSuccess()) {
            return new ResponseDTO<>(200, "获取用户信息成功！", userdata);
        }
        return new ResponseDTO<>(200, a.getMessage(), userdata);
//            return a;
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 注销登录，清除Session中的用户信息

        session.removeAttribute("user");
        redisUtil.delete("debug");
        // 注销登录
        StpUtil.logout();
        System.out.println("注销成功！");

        return "redirect:/login";

    }




    @PostMapping("/userDelete")
    @SaCheckPermission("user:delete")
    @ResponseBody
    public ResponseDTO<Users> delete(@RequestParam Long id) {
        userService.delete(id);
        return new ResponseDTO<>(200, "删除信息成功！", null);
    }
    @LogRequest
    @PostMapping("/getuserinfo")
    @ResponseBody
    public ResponseDTO<Users> getuserinfo(HttpServletRequest request) {
//            List<Users> findUser = userService.list();
//            model.addAttribute("user",findUser );
        // 校验是否登录
        StpUtil.checkLogin();
        //登录成功之后，将用户信息存入session
        HttpSession session = request.getSession();

        Users user = (Users) session.getAttribute("user");


        return new ResponseDTO<>(200, "获取用户信息成功！", user);
    }

    /*
     * 根据角色id获取对应的权限
     * */
    @GetMapping("/getMenus")
    @ResponseBody
    // 定义一个方法，用于获取资源信息
    public Map<String, Object> getMenus(HttpSession session) {
        // 创建一个map对象，用于存储资源信息
        Map<String, Object> map = new HashMap<>();
        // 创建一个homeInfo对象，用于存储首页信息
        Map<String, Object> homeInfo = new HashMap<>();
        homeInfo.put("title", "首页");
        homeInfo.put("icon", "fa fa-home");
        homeInfo.put("href", "welcome-1.html");
        // 将homeInfo对象添加到map中
        map.put("homeInfo", homeInfo);
        // 创建一个logoInfo对象，用于存储logo信息
        Map<String, Object> logoInfo = new HashMap<>();
        logoInfo.put("title", "测试ERP");
        logoInfo.put("image", "static/images/logo.png");
        logoInfo.put("href", "");
        // 将logoInfo对象添加到map中
        map.put("logoInfo", logoInfo);
        // 创建一个menuInfo列表，用于存储菜单信息
        List<Object> menuInfo = new ArrayList<>();
        // 获取当前登录人保存的getRoleId信息
        List<Long> roleId = (List<Long>) session.getAttribute("roleId");
        // 打印测试当前登陆的角色id是多少是否与数据库中id相对应。
        System.out.println(roleId);
        // 根据roleId查询后面对应的资源菜单
        List<MenuVO> resource = menuService.getMenuByRoleId(roleId);
        System.out.println(resource);
        // 测试查询到的菜单

        // 遍历资源列表，将资源添加到menuInfo中
        resource.forEach(t -> {

            menuInfo.add(t);
            System.out.println(t);
        });
        // 将menuInfo添加到map中
        map.put("menuInfo", menuInfo);
        // 返回map对象
        return map;
    }
}
